package ui;


import cerebrum.common.EmptyChecker;
import cerebrum.common.FileUtil;
import cerebrum.controller.WallpaperCerebrum;
import com.alibaba.fastjson.JSONArray;
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.*;
import javafx.scene.paint.Paint;
import javafx.stage.DirectoryChooser;
import ui.panel.SetUp;
import ui.panel.Welcome;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author renkaijiang
 * 程序的全局操控类
 */
public class Controller {

    public static Welcome welcome;
    public static SetUp setUp;

    public static Welcome getWelcome() {
        return welcome;
    }

    public static void setWelcome(Welcome welcome) {
        Controller.welcome = welcome;
    }

    public static SetUp getSetUp() {
        return setUp;
    }

    public static void setSetUp(SetUp setUp) {
        Controller.setUp = setUp;
    }

    public Controller() throws IOException, AWTException {
        welcome = new Welcome();
        welcome.show();
        setUp = new SetUp();
    }


    /**
     * 实现各个页面的交互，实现最终程序的运行
     *
     * @param main
     */
    public void exec(Main main) throws IOException {
        wallpaperTypeMessage();
        refreshFrequency();
        isCleaningImages();
        imagesUpdateDate();
        selectFolder();
        setUpExec();
        openSourceURL(main);
    }

    /**
     * 该方法通过页面对象 以及给定的id 选择页面的元素  用法:TextField t = (TextField)$(dialog,"UserName");
     * 这样选出登入框对象的id为UserName的输入框 之后就可以为 t 绑定事件了
     *
     * @param window
     * @param id
     * @return
     */
    public Object $(Window window, String id) {
        return (Object) window.getRoot().lookup("#" + id);
    }
//---------------------------- 设置界面 数据提交----------------------------

    /**
     * 设置界面的运行
     */
    public void setUpExec() {
        ((Button) $(setUp, "enter")).setOnAction(event -> {
            JSONArray likeTypes = userLikeWallpaperType();

            if (likeTypes.size() < 2) {
                //设置提示
                setErrorTip(setUp, "wallpaper_type_message", "              壁纸类型请至少选中两项");
                //设置提示颜色
                ((Label) $(setUp, "wallpaper_type_message")).setTextFill(Paint.valueOf("#DC381F"));
                //设置不在隐藏
                ((Label) $(setUp, "wallpaper_type_message")).setVisible(true);
                ((Label) $(setUp, "wallpaper_type_message")).setManaged(true);

                return;
            }
            //壁纸保存路径
            String folderPath = getFolderPath();
            if (EmptyChecker.isEmpty(folderPath)) {
                String str = "请先选择壁纸路径!";
                setFolderStyle(str,"#FF6347","选择保存路径");
                return;
            }

            //壁纸刷新频率
            int refreshFrequencyValue = getRefreshFrequencyValue();
            //壁纸下载量
            long imagesDownloadNum = imagesDownloadNum();
            //是否清除下载的壁纸
            int cleaningImagesValue = isCleaningImagesValue();
            //壁纸更新时间
            int imagesUpdateDateValue = imagesUpdateDateValue();


            setUpSaveFile(likeTypes,
                    refreshFrequencyValue,
                    imagesDownloadNum,
                    cleaningImagesValue,
                    imagesUpdateDateValue,
                    folderPath);
        });
    }

    private void setUpSaveFile(JSONArray likeTypes,
                               int refreshFrequencyValue,
                               long imagesDownloadNum,
                               int cleaningImagesValue,
                               int imagesUpdateDateValue,
                               String folderPath) {
        HashMap obj = new HashMap();
        obj.put("is_user_set_up", true);
        obj.put("likeType", likeTypes);
        obj.put("frequency", refreshFrequencyValue * 1000);
        obj.put("downloadNum", imagesDownloadNum);
        obj.put("isCleaningImages", cleaningImagesValue);
        obj.put("updateImagesDate", imagesUpdateDateValue * 60);//分钟转化成秒
        obj.put("wallpaperFilePath", folderPath);

        //将用户设置写入设置文件持久化
        FileUtil.writeFunctionRecord(obj);
        setUp.hide();
        //后台程序开始运行
        WallpaperCerebrum.startRun(true);
    }

    /**
     * user Choose Like Wallpaper Type
     */
    private JSONArray userLikeWallpaperType() {
        boolean wallpaperTypeBing = ((CheckBox) $(setUp, "wallpaper_type_bing")).isSelected();
        boolean wallpaperTypeComic = ((CheckBox) $(setUp, "wallpaper_type_comic")).isSelected();
        boolean wallpaperTypeScenery = ((CheckBox) $(setUp, "wallpaper_type_scenery")).isSelected();
        boolean wallpaperTypeBeauty = ((CheckBox) $(setUp, "wallpaper_type_beauty")).isSelected();
        boolean wallpaperTypeGufeng = ((CheckBox) $(setUp, "wallpaper_type_gufeng")).isSelected();
        boolean wallpaperTypeXiandai = ((CheckBox) $(setUp, "wallpaper_type_xiandai")).isSelected();
        boolean wallpaperTypeQuadraticElementBeauty = ((CheckBox) $(setUp, "wallpaper_type_quadratic_element_beauty")).isSelected();
        boolean wallpaperTypeSexy = ((CheckBox) $(setUp, "wallpaper_type_sexy")).isSelected();
        //至少选中两项
        JSONArray jsonArray = new JSONArray();
        if (wallpaperTypeBing) {
            jsonArray.add("bing");
        }
        if (wallpaperTypeComic) {
            jsonArray.add("comic");
        }
        if (wallpaperTypeScenery) {
            jsonArray.add("scenery");
        }
        if (wallpaperTypeBeauty) {
            jsonArray.add("beauty");
        }
        if (wallpaperTypeGufeng) {
            jsonArray.add("gufeng");
        }
        if (wallpaperTypeXiandai) {
            jsonArray.add("xiandai");
        }
        if (wallpaperTypeQuadraticElementBeauty) {
            jsonArray.add("quadratic_element_beauty");
        }
        if (wallpaperTypeSexy) {
            jsonArray.add("sexy");
        }
        return jsonArray;
    }

    //获取刷新频率用户选中了哪一个
    private int getRefreshFrequencyValue() {
        boolean refreshFrequency3 = ((RadioButton) $(setUp, "refresh_frequency_3")).isSelected();
        boolean refreshFrequency5 = ((RadioButton) $(setUp, "refresh_frequency_5")).isSelected();
        boolean refreshFrequency10 = ((RadioButton) $(setUp, "refresh_frequency_10")).isSelected();
        boolean refreshFrequency30 = ((RadioButton) $(setUp, "refresh_frequency_30")).isSelected();

        if (refreshFrequency3) {
            return 3;
        }
        if (refreshFrequency5) {
            return 5;
        }
        if (refreshFrequency10) {
            return 10;
        }
        if (refreshFrequency30) {
            return 30;
        }
        return 0;
    }

    //获取壁纸下载量
    private long imagesDownloadNum() {
        double downloadNum = ((Slider) $(setUp, "download_num")).getValue();
        return Math.round(downloadNum);
    }

    private String getFolderPath() {
        return ((Label) $(setUp, "select_folder_path")).getText();
    }

    /**
     * 获取用户设置的多久清除一次下载的壁纸
     */
    private int isCleaningImagesValue() {
        boolean cleaningImagesNo = ((RadioButton) $(setUp, "cleaning_images_no")).isSelected();
        boolean cleaningImagesLastTime = ((RadioButton) $(setUp, "cleaning_images_last_time")).isSelected();
        boolean cleaningImagesThree = ((RadioButton) $(setUp, "cleaning_images_three")).isSelected();
        boolean cleaningImagesTen = ((RadioButton) $(setUp, "cleaning_images_ten")).isSelected();
        if (cleaningImagesNo) {
            return 0;
        }
        if (cleaningImagesLastTime) {
            return 1;
        }
        if (cleaningImagesThree) {
            return 3;
        }
        if (cleaningImagesTen) {
            return 5;
        }
        return 0;
    }

    /**
     * 获取用户选择的壁纸更新时间
     */
    private int imagesUpdateDateValue() {
        boolean imagesUpdateDateFive = ((RadioButton) $(setUp, "images_update_date_five")).isSelected();
        boolean imagesUpdateDateTen = ((RadioButton) $(setUp, "images_update_date_ten")).isSelected();
        boolean imagesUpdateDateFifteen = ((RadioButton) $(setUp, "images_update_date_fifteen")).isSelected();
        boolean imagesUpdateDateThirty = ((RadioButton) $(setUp, "images_update_date_thirty")).isSelected();
        if (imagesUpdateDateFive) {
            return 5;
        }
        if (imagesUpdateDateTen) {
            return 10;
        }
        if (imagesUpdateDateFifteen) {
            return 15;
        }
        if (imagesUpdateDateThirty) {
            return 30;
        }
        return 0;
    }

    //--------------------------------- 页面联动控制----------------------------------------------
    //写真勾选警告提示
    private void wallpaperTypeMessage() {
        ((CheckBox) $(setUp, "wallpaper_type_sexy")).setOnAction(event -> {
            boolean pressed = ((CheckBox) $(setUp, "wallpaper_type_sexy")).isSelected();
            if (pressed) {
                ((Label) $(setUp, "wallpaper_type_message")).setText("（非常不建议办公环境下勾选）");
                ((Label) $(setUp, "wallpaper_type_message")).setTextFill(Paint.valueOf("#6CBB3C"));
                ((Label) $(setUp, "wallpaper_type_message")).setVisible(true);
                ((Label) $(setUp, "wallpaper_type_message")).setManaged(true);
            } else {
                ((Label) $(setUp, "wallpaper_type_message")).setVisible(false);
                ((Label) $(setUp, "wallpaper_type_message")).setManaged(false);
            }

        });
    }


    //壁纸刷新频率单选控制
    private void refreshFrequency() {
        ((RadioButton) $(setUp, "refresh_frequency_3")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "refresh_frequency_3")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "refresh_frequency_5")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_10")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "refresh_frequency_5")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "refresh_frequency_5")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "refresh_frequency_3")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_10")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "refresh_frequency_10")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "refresh_frequency_10")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "refresh_frequency_3")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_5")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_30")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "refresh_frequency_30")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "refresh_frequency_30")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "refresh_frequency_5")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_10")).setSelected(false);
                ((RadioButton) $(setUp, "refresh_frequency_3")).setSelected(false);
            }

        });
    }

    //是否清除已使用的壁纸单选控制
    private void isCleaningImages() {
        ((RadioButton) $(setUp, "cleaning_images_no")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "cleaning_images_no")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "cleaning_images_last_time")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_three")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "cleaning_images_last_time")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "cleaning_images_last_time")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "cleaning_images_no")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_three")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "cleaning_images_three")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "cleaning_images_three")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "cleaning_images_no")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_last_time")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_ten")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "cleaning_images_ten")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "cleaning_images_ten")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "cleaning_images_no")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_three")).setSelected(false);
                ((RadioButton) $(setUp, "cleaning_images_last_time")).setSelected(false);
            }

        });
    }

    //壁纸更新时间单选控制
    private void imagesUpdateDate() {
        ((RadioButton) $(setUp, "images_update_date_five")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "images_update_date_five")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "images_update_date_ten")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_fifteen")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "images_update_date_ten")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "images_update_date_ten")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "images_update_date_five")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_fifteen")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "images_update_date_fifteen")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "images_update_date_fifteen")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "images_update_date_five")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_ten")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_thirty")).setSelected(false);
            }

        });
        ((RadioButton) $(setUp, "images_update_date_thirty")).setOnAction(event -> {
            boolean pressed = ((RadioButton) $(setUp, "images_update_date_thirty")).isSelected();
            if (pressed) {
                ((RadioButton) $(setUp, "images_update_date_five")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_ten")).setSelected(false);
                ((RadioButton) $(setUp, "images_update_date_fifteen")).setSelected(false);
            }

        });

    }

    private void selectFolder() {
        ((Button) $(setUp, "select_folder")).setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File file = directoryChooser.showDialog(setUp);
            if (EmptyChecker.notEmpty(file)) {
                String path = file.getPath();//选择的文件夹路径
                //设置提示
                setFolderStyle(path,"#00ffff","重新选择");
            }

        });
    }

    private void setFolderStyle(String message, String style,String buttonName) {
        setErrorTip(setUp, "select_folder_path", message);
        //设置提示颜色
        ((Label) $(setUp, "select_folder_path")).setTextFill(Paint.valueOf(style));
        //设置不在隐藏
        ((Label) $(setUp, "select_folder_path")).setVisible(true);
        ((Label) $(setUp, "select_folder_path")).setManaged(true);

        ((Button) $(setUp, "select_folder")).setLayoutX(distance(message));
        ((Button) $(setUp, "select_folder")).setText(buttonName);
    }

    //点击文本打开网站
    private void openSourceURL(Application application) {
        ((Button) $(setUp, "message1")).setOnAction(event -> {
            application.getHostServices().showDocument("https://gitee.com/missyouch/desserts");
        });
        ((Button) $(setUp, "message2")).setOnAction(event -> {
            application.getHostServices().showDocument("https://gitee.com/missyouch/desserts");
        });

    }

    //计算像素点
    private double distance(String path) {
        double dd = 11.0;
        if (isContainChinese(path)) {
            dd = 16.0;
        }
        double dou = 125 + (path.length() * dd);
        return dou >= 395.0 ? 385.0 : dou;
    }

    //判断有无中文
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 设置错误提示
     *
     * @param id
     * @param Text
     */
    public void setErrorTip(Window window, String id, String Text) {
        ((Label) $(window, id)).setText(Text);
    }
}